package com.leyou.item.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.SkuDto;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.dto.SpuDetailDTO;
import com.leyou.item.entitiy.*;
import com.leyou.item.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private TbSpuService spuService;
    @Autowired
    private TbCategoryService categoryService;
    @Autowired
    private TbBrandService brandService;
    @Autowired
    private TbSkuService skuService;
    @Autowired
    private TbSpuDetailService spuDetailService;

    @Override
    public PageResult<SpuDTO> findSpuByPage(Integer page, Integer rows, String key, Boolean saleable) {
        //分页信息
        IPage<TbSpu> spuPage = new Page<>(page,rows);
        //查询条件
        QueryWrapper<TbSpu> queryWrapper = new QueryWrapper<>();
        //模糊查询 商品 名称
        if(!StringUtils.isEmpty(key)){
            queryWrapper.lambda().like(TbSpu::getName,key);
        }
        //是否上下架
        if(saleable != null){
            queryWrapper.lambda().eq(TbSpu::getSaleable,saleable);
        }
        //排序
        queryWrapper.lambda().orderByDesc(TbSpu::getUpdateTime);
        //分页查询
        IPage<TbSpu> spuIPage = spuService.page(spuPage, queryWrapper);
        if(spuIPage == null || CollectionUtils.isEmpty(spuIPage.getRecords())){
            throw  new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        //转bean
        List<SpuDTO> spuDTOS = BeanHelper.copyWithCollection(spuIPage.getRecords(), SpuDTO.class);
        //处理 品牌名称和分类名称
        this.handleBrandAndCategoryName(spuDTOS);
        //包装PageResult
        PageResult<SpuDTO> pageResult = new PageResult<SpuDTO>(spuIPage.getTotal(),spuIPage.getPages(),spuDTOS);
        return pageResult;
    }

    @Override
    public void saveGoods(SpuDTO spuDTO) {
        //保存spu信息
        TbSpu tbSpu = BeanHelper.copyProperties(spuDTO, TbSpu.class);
        boolean bSpu = spuService.save(tbSpu);
        if(!bSpu){
            throw  new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
        Long spuId = tbSpu.getId();
        //详情表
        SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
        TbSpuDetail tbSpuDetail = BeanHelper.copyProperties(spuDetailDTO, TbSpuDetail.class);
        tbSpuDetail.setSpuId(spuId);
        //保存spudetail信息
        boolean bDetail = spuDetailService.save(tbSpuDetail);
        if(!bDetail){
            throw  new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
        //保存sku信息
        List<SkuDto> skus = spuDTO.getSkus();
        if(!CollectionUtils.isEmpty(skus)){
            List<TbSku> tbSkuList = skus.stream().map(skuDTO -> {
                skuDTO.setSpuId(spuId);
                return BeanHelper.copyProperties(skuDTO, TbSku.class);
            }).collect(Collectors.toList());
            boolean bSku = skuService.saveBatch(tbSkuList);
            if(!bSku){
                throw  new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
            }
        }
    }

    //上下架
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSaleable(Long id, Boolean saleable) {
        //更新spu
        TbSpu tbSpu = new TbSpu();
        tbSpu.setId(id);
        tbSpu.setSaleable(saleable);
        spuService.updateById(tbSpu);
        //更新sku
        UpdateWrapper<TbSku> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(TbSku::getSpuId,id);
        updateWrapper.lambda().set(TbSku::getEnable,saleable);
        skuService.update(updateWrapper);
    }

    /*
    *
    * 修改的回显
    *
    * */
    @Override
    public SpuDetailDTO querySpuDetailById(Long id) {
        TbSpuDetail spuDetail = spuDetailService.getById(id);
        if(spuDetail == null){
            throw  new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyProperties(spuDetail,SpuDetailDTO.class);
    }

    //添加
    private void handleBrandAndCategoryName(List<SpuDTO> spuDTOList){
        for (SpuDTO spuDTO : spuDTOList) {
            //商品所属 分类
            List<Long> categoryIdList = spuDTO.getCategoryIds();
            Collection<TbCategory> tbCategoryCollection = categoryService.listByIds(categoryIdList);
            String categoryName = tbCategoryCollection.stream().map(TbCategory::getName).collect(Collectors.joining("/"));
            spuDTO.setCategoryName(categoryName);
            //商品品牌
            Long brandId = spuDTO.getBrandId();
            TbBrand brand = brandService.getById(brandId);
            spuDTO.setBrandName(brand.getName());

        }
    }
}
